package org.internna.ossmoney.services.impl;

import java.math.BigDecimal;
import org.internna.ossmoney.model.Payee;
import org.internna.ossmoney.model.Account;
import org.internna.ossmoney.util.DateUtils;
import org.internna.ossmoney.model.Investment;
import org.internna.ossmoney.model.Subcategory;
import org.internna.ossmoney.model.AccountTransaction;
import org.internna.ossmoney.model.security.UserDetails;
import org.internna.ossmoney.model.InvestmentTransaction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class InvestmentService implements org.internna.ossmoney.services.InvestmentService {

	@Override public void addInvestment(UserDetails user, Account account, InvestmentTransaction transaction, double commision) {
		String subcat = transaction.getAccountTransaction().getSubcategory().getCategory();
		Subcategory subcategory = Subcategory.findBySubcategory(subcat, user);
		Investment investment = Investment.findInvestment(transaction.getInvestment().getId());
		investment.addInvestment(transaction);
		BigDecimal amount = transaction.getAccountTransaction().getAmount();
		if ((amount == null) || BigDecimal.ZERO.equals(amount)) {
			amount = new BigDecimal(transaction.getQuantity() * transaction.getPrice().getPrice());
		} else {
			transaction.setQuantity(0D);
		}
		amount = amount.abs();
		if ("category.investment.buy".equals(subcat)) {
			amount = amount.negate();
		}
		transaction.getPrice().addTransaction(transaction);
		transaction.getAccountTransaction().setAmount(amount);
		transaction.getAccountTransaction().setAccount(account);
		transaction.getAccountTransaction().setPayee(investment);
		transaction.getAccountTransaction().setInvestment(transaction);
		transaction.getAccountTransaction().setSubcategory(subcategory);
		transaction.getAccountTransaction().persist();
		if (commision != 0D) {
			BigDecimal charge = new BigDecimal(commision).abs();
			Subcategory chargeCategory = Subcategory.findBySubcategory("category.bankcharges", user);
			AccountTransaction bankCharge = AccountTransaction.createInstance(account, Payee.findByFinancialInstitution(account.getHeldAt()), chargeCategory, charge, DateUtils.nextDate(transaction.getAccountTransaction().getOperationDate()), null);
			bankCharge.persist();
		}
	}

}
